<?php
class Model_Cart_Mapper extends App_Model_Mapper
{
	protected $_map = array(
	   'id'         => 'id', 
	   'user_id'    => 'user_id',
	   'product_id' => 'product_id',
	   'count'      => 'count',
	   'order_id'   => 'order_id'
	);
	
	protected function _setTable()
	{
		return new Model_DbTable_Cart();
	}
	
	public function loadByUserId($id = null)
	{
		if($id === null) {
		    $cache  = Zend_Registry::get('cache');
		    $cart   =   $cache->load($_COOKIE['uid']);
		    if(!$cart){
		        return new Model_Cart();
		    } else {
		        return $cart;
		    }
		} else {
		    $cart = new Model_Cart();
		    $cart->user_id = $id;
		    return $cart;
		}
	}
	
	public function save($cart)
	{
	    if(Zend_Auth::getInstance()->hasIdentity()){
	        $products = $cart->products;
	        $this->_table->delete('user_id = ' . $cart->user_id);
	        foreach($products as $product){
	            $this->_table->insert(array('user_id'=>$cart->user_id, 'product_id'=>$product->id, 'date' => new Zend_Db_Expr('now()')));
	        }
	    } else {
            $cache  = Zend_Registry::get('cache');
            $cache->save($cart, $_COOKIE['uid']);
	    }
	}
	
	public function getProducts($user_id)
	{
	    if($user_id === null){
            return array();
	    } else {
	        $db = Zend_Registry::get('db');
	        $select = $db->select()->from(array('c'=>'cart'))
	           ->join(array('p'=>'product'), 'c.product_id = p.id')
	           ->where('c.user_id  = ' . $user_id);
	        $result = $db->fetchAll($select);
	        $productMapper = new Model_Product_Mapper();
	        return $productMapper->getArray($result);
	        return array();
	    }
	    
	}

} 